package com.online.studyonline.controller;

import com.online.studyonline.pojo.Result;
import com.online.studyonline.pojo.ResultT;
import com.online.studyonline.pojo.User;
import com.online.studyonline.service.UserService;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Validated
public class UserController {

    @Autowired
    UserService userService;
    @PostMapping("/register")
    public ResultT<String> register(@Pattern(regexp = "^[a-zA-Z0-9]{5,12}$")String username,
                                    @Pattern(regexp = "^[a-zA-Z0-9]{5,12}$")String password,
                                    @Pattern(regexp = "^[a-zA-Z0-9]{5,12}$")String repwd){
        if (!password.equals(repwd)){
            return ResultT.error("两次密码不一致");
        }

        userService.addUser(username,password);
        return ResultT.success();
    }

    @PostMapping ("/login")
    public ResultT<User> login(@Pattern(regexp = "^[a-zA-Z0-9]{5,12}$") String username,
                              @Pattern(regexp = "^[a-zA-Z0-9]{5,12}$")String password){
//        System.out.println(username+' '+password);
        User user = userService.getByUsername(username);
        if (user==null){
            return ResultT.error("用户名错误");
        }
        if(user.getPasswordHash().equals(password)){
            return ResultT.success(user);
        }
        else {
            return ResultT.error("密码错误");
        }
    }


    @GetMapping("/getUser")
    public Result getUser(@RequestParam("username") String username){
//        System.out.println(username);
        return Result.success(userService.getuser(username));
    }
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        userService.update(user.getSchool(),user.getUsername());
        return Result.success();
    }
    @PostMapping("/updatePhone")
    public Result updatePhone(@RequestBody User user){
        userService.updatePhone(user.getPhoneNumber(),user.getUsername());
        return Result.success();
    }
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody User user){
        userService.updatePassword(user.getPasswordHash(),user.getUsername());
        return Result.success();
    }
}
